import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cartItems: JSON.parse(localStorage.getItem("cartItems")) || [],
  },
  mutations: {
    // 添加商品到购物车
    ADD_TO_CART(state, product) {
      // 检查是否已存在相同商品（相同ID和规格）
      const existingItem = state.cartItems.find(
        (item) => item.id === product.id && item.spec === product.spec
      );

      if (existingItem) {
        // 如果已存在，增加数量
        existingItem.quantity += product.quantity;
      } else {
        // 如果不存在，添加新商品
        state.cartItems.push({
          ...product,
          selected: true, // 默认选中
        });
      }

      // 持久化到localStorage
      localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
    },

    // 从购物车移除商品
    REMOVE_FROM_CART(state, itemId) {
      state.cartItems = state.cartItems.filter((item) => item.id !== itemId);
      localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
    },

    // 更新商品数量
    UPDATE_QUANTITY(state, { id, quantity }) {
      const item = state.cartItems.find((item) => item.id === id);
      if (item) {
        item.quantity = quantity;
        localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
      }
    },

    // 切换商品选中状态
    TOGGLE_SELECT(state, id) {
      const item = state.cartItems.find((item) => item.id === id);
      if (item) {
        item.selected = !item.selected;
        localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
      }
    },

    // 全选/取消全选
    TOGGLE_ALL_SELECT(state, selected) {
      state.cartItems.forEach((item) => {
        item.selected = selected;
      });
      localStorage.setItem("cartItems", JSON.stringify(state.cartItems));
    },

    // 清空购物车
    CLEAR_CART(state) {
      state.cartItems = [];
      localStorage.removeItem("cartItems");
    },
  },
  actions: {
    // 添加商品到购物车
    ADD_TO_CART({ commit }, product) {
      return new Promise((resolve) => {
        commit("ADD_TO_CART", product);
        resolve();
      });
    },

    // 从购物车移除商品
    removeFromCart({ commit }, itemId) {
      return new Promise((resolve) => {
        commit("REMOVE_FROM_CART", itemId);
        resolve();
      });
    },

    // 更新商品数量
    UPDATE_QUANTITY({ commit }, payload) {
      commit("UPDATE_QUANTITY", payload);
    },

    // 切换商品选中状态
    TOGGLE_SELECT({ commit }, id) {
      commit("TOGGLE_SELECT", id);
    },

    // 全选/取消全选
    TOGGLE_ALL_SELECT({ commit, state }) {
      const allSelected = state.cartItems.every((item) => item.selected);
      commit("TOGGLE_ALL_SELECT", !allSelected);
    },

    // 清空购物车
    CLEAR_CART({ commit }) {
      return new Promise((resolve) => {
        commit("CLEAR_CART");
        resolve();
      });
    },

    // 更新购物车数量显示
    UPDATE_CART_COUNT({ state }) {
      // 可以在这里添加其他更新逻辑
      console.log("当前购物车商品数量:", state.cartItems.length);
    },
  },
  getters: {
    // 获取购物车所有商品
    cartItems: (state) => state.cartItems,

    // 计算已选商品数量
    selectedCount: (state) => {
      return state.cartItems.filter((item) => item.selected).length;
    },

    // 计算已选商品总金额
    totalAmount: (state) => {
      return state.cartItems
        .filter((item) => item.selected)
        .reduce((total, item) => total + item.price * item.quantity, 0)
        .toFixed(2);
    },

    // 检查是否全选
    allSelected: (state) => {
      return (
        state.cartItems.length > 0 &&
        state.cartItems.every((item) => item.selected)
      );
    },

    // 获取购物车商品总数
    cartItemCount: (state) => {
      return state.cartItems.reduce((total, item) => total + item.quantity, 0);
    },
  },
});
